<template>
  <div class="">
    {{ addForm }}
    {{ images }}
    <el-form ref="ruleFormRef" style="max-width: 600px" :model="addForm" :rules="rules" label-width="auto"
      class="demo-ruleForm" status-icon>
      <el-form-item label="店名" prop="name">
        <el-input v-model="addForm.name" aria-placeholder="请输入标题" />
      </el-form-item>
      <el-form-item label="营业时间" prop="startTime">
        <el-time-picker v-model="addForm.startTime" value-format="HH:mm" placeholder="起始时间" />
        <el-time-picker v-model="addForm.endTime" value-format="HH:mm"  placeholder="结束时间" />
      </el-form-item>
      <el-form-item label="服务范围" prop="services">
        <el-select v-model="addForm.services" placeholder="请选择类型">
          <el-option v-for="(item, index) in service" :key="item.id" :value="item.name" :label="item.name" />
        </el-select>
      </el-form-item>
      <el-form-item label="店主" prop="username">
        <el-input v-model="addForm.username" aria-placeholder="请输入标题" />
      </el-form-item>
      <el-form-item label="联系电话" prop="tel">
        <el-input v-model="addForm.mobile" aria-placeholder="请输入标题" />
      </el-form-item>
      <el-form-item label="门店介绍" prop="content">
        <RichText v-model:content="addForm.intro"></RichText>
      </el-form-item>
      <el-form-item label="门店地址" prop="address">
        <el-input v-model="addForm.address" aria-placeholder="请输入标题" />
      </el-form-item>
      <el-form-item label="门店logo" prop="logo">
        <el-upload :headers="headers" class="avatar-uploader" :action="updataurl + 'upload/add'" :show-file-list="false"
          :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
          <img v-if="addForm.logo" :src="baseUrl + addForm.logo" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="门店图片" prop="images">
        <el-upload v-model:file-list="images" :headers="headers" class="upload-demo" :action="updataurl + 'upload/add'"
          :on-preview="handleAvatarSuccess" :on-remove="beforeAvatarUpload" list-type="picture">
          <el-button type="primary">上传图片</el-button>
          <template #tip>
            <div class="el-upload__tip">
              文件应为png或jpg格式且大小不超过2M
            </div>
          </template>
        </el-upload>
      </el-form-item>
      <el-form-item label="" prop="name">
        <el-button type="primary" @click="onSubmit">{{ addForm.id == 0 ? "添加" : "修改" }}</el-button>
        <el-button @click="router.go(-1)">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang='ts' setup>
import { ref, watch, reactive, onMounted } from "vue"
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import { useRoute, useRouter } from "vue-router";
import { useStore } from '../../store/index'
import { ElMessage } from 'element-plus'
import type { UploadProps,UploadUserFile } from 'element-plus'
import { storeserviceslist,storesadd,storesonelist } from '../../service/stores/stores'
import { addshop } from '../../service/stores/type'
import { storeToRefs } from "pinia";
import RichText from "../../components/RichText.vue";



const usestore = useStore()
const { token } = storeToRefs(usestore)
const router = useRouter()
const baseUrl = import.meta.env.VITE_IMG_URL
const service = ref<any>([])
const updataurl = import.meta.env.VITE_BASE_URL
const headers = {
  Authorization: token.value
}

const images = ref<any>([])
const getservice = async () => {
  let res = await storeserviceslist()
  service.value = res.data.list
}
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
) => {
  if (response.errCode === 10000) {
    addForm.logo = response.data;
  }
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('文件应为png或jpg格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('文件大小不能超过2M!')
    return false
  }
  return true
}
const addstores = async () => {
  let res:any = await storesadd(addForm)
  if (res.errCode === 10000) {
    ElMessage.success('添加成功')
   return router.go(-1)
  }
  ElMessage.warning('添加失败')
}
const onSubmit = () => {

  addForm.images= images.value.map((item:any)=>{
      if (item.response) {
        return {url:item.response.data}
      }
      return {url:item.name}
  })
  addstores()
}

const addForm = reactive<addshop>({
  address: '',
  endTime: '',
  id: 0,
  images: [],
  intro: '',
  logo: '',
  mobile: '',
  name: '',
  pass: null,
  services: null,
  startTime: '',
  tel: '',
  username: ''
})


const rules = reactive<FormRules<any>>({
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
  ],
  picture: [
    { required: true, message: '请输入标题', trigger: 'blur' },
  ],
  state: [
    { required: true, message: '请输入标题', trigger: 'blur' },
  ],
  content: [
    { required: true, message: '请输入标题', trigger: 'blur' },
  ],
  type: [
    { required: true, message: '请输入标题', trigger: 'blur' },
  ],
})

const getstoresonelist  = async(id:number)=>{
  let res:any = await storesonelist(id)
  if (res.errCode==10000) {
    console.log(res);
    images.value = res.data.images.map((item:any)=>{
    return { 
      name:item.url,
      url:baseUrl+item.url}})
    Object.assign(addForm,res.data)
    addForm.images=[]
  }
}
const route = useRoute()
onMounted(() => {
  getservice()
  const id = route.query.id as any
  if (id) {
    getstoresonelist(id)
  }
})
</script>


<style scoped>
.avatar-uploader .avatar {
  width: 78px;
  height: 78px;
  display: block;
}
/deep/ .avatar-uploader .el-upload {
  width: 80px;
  height: 80px;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
</style>
